<template>
  <div :style="{'background-image': 'url(' + currentBackgroundImage + ')'}" class="login">
    <!--登录form-->
    <transition name="el-zoom-in-center">
      <el-form v-show="isShowLogin === true" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">线上学生生源地助学贷款系统</h3>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-link @click="isShowLogin = false" style="float: right" type="primary">没有账号,前往注册</el-link>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </transition>

    <!--注册form-->
    <transition name="el-zoom-in-center">
      <el-form v-show="isShowLogin === false" ref="registryForm" :model="registryForm" :rules="registryRules" class="login-form">
        <h3 class="title">线上学生生源地助学贷款系统</h3>
        <el-form-item>
          <el-input v-model="registryForm.userName" type="text" auto-complete="off" placeholder="请输入账号注册">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="registryForm.password"
            type="password"
            auto-complete="off"
            placeholder="请输入密码注册"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-if="isShowSendSms === true" v-model="registryForm.phonenumber" placeholder="请输入手机号" style="width: 200px">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <el-input v-else v-model="smsCode" placeholder="请输入短信验证码" style="width: 200px">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <el-button size="mini" v-if="isShowSendSms === true" @click="sendSms" style="margin-left: 20px;" effect="dark">获取手机验证码</el-button>
          <el-button size="mini" v-if="isShowPutSms === true" style="margin-left: 20px;" effect="dark">请 {{ countNum }} 秒后再获取</el-button>
          <el-button size="mini" v-if="isShowReSend" @click="sendSms" style="margin-left: 20px;" effect="dark">重新获取验证码</el-button>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-link @click="isShowLogin = true" style="float: right" type="primary">已有账号,前往登录</el-link>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="success"
            style="width:100%;"
            @click.native.prevent="handleRegistry"
          >
            <span v-if="!loading">注册</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </transition>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>梧州学院 谭卢钢 毕业设计</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { registry } from '../api/system/user'
import { toSendRegistrySms } from '../api/dysms/dysms'

export default {
  name: "Login",
  data() {
    return {
      timer: '',
      backgroundImageArray: [
        require('../assets/image/background.jpg'),
        require('../assets/image/backgroud2.jpg'),
        require('../assets/image/wallhaven-8x926j.jpg'),
        require('../assets/image/和平精英.jpg'),
      ],
      currentBackgroundImage: require('../assets/image/background.jpg'),
      isShowReSend: false,
      sms: '',
      smsCode: '',
      isShowSendSms: true,
      isShowPutSms: false,
      countNum: 20,
      phone: '',
      isShowLogin: true,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        // 密码 admin123
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      registryForm: {
        userName: "",
        // 密码 admin123
        password: "",
        phonenumber: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      registryRules: {
        userName: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        phonenumber: [
          { required: true, trigger: "blur", message: "短信验证码不能为空" }
        ]
      },
      loading: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();

     this.timer = setInterval(() => {
        const random = parseInt(Math.random() * 4)
        this.currentBackgroundImage = this.backgroundImageArray[random]
      }, 6000)

  },
  methods: {
    handleRegistry() {
      if (this.smsCode === this.sms) {
        console.log(this.registryForm)
        if (!this.registryForm.userName) {
          this.msgInfo('请输入账号注册!')
        } else if (!this.registryForm.password) {
          this.msgInfo('请输入密码注册!')
        }else if (!this.smsCode) {
          this.msgInfo('请输入短信验证码!')
        } else if (this.registryForm.userName && this.registryForm.password && this.smsCode) {
          registry(this.registryForm).then(res => {
            if (res) {
              this.msgSuccess('新用户注册成功!')
              this.isShowLogin = true
            }
          })
        }
      } else {
        this.msgInfo('请输入正确的手机注册码')
      }
    },
    sendSms() {
      this.isShowReSend = false
      if (!this.registryForm.phonenumber) {
        this.msgInfo('请输入手机号码!')
      } else {
        this.isShowSendSms = false
        this.isShowPutSms = true
        // 发送注册码
        toSendRegistrySms({phone: this.registryForm.phonenumber}).then(res => {
          this.msgSuccess('验证码已发送，请注意查收!')
          this.sms = res.sms
          console.log(res)
        })

        // 倒计时
        let timer = setInterval(() => {
          if (this.countNum > 0) {
            this.countNum--
          } else if (this.countNum === 0) {
            this.isShowPutSms = false
            this.countNum = 20
            this.isShowReSend = true
          }
        }, 1000)

      }

    },
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
/*  background-image: url("../assets/image/wallhaven-8x926j.jpg");*/
  background-image: url("../assets/image/backgroud2.jpg");
/*  background-image: url("https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg");*/
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #191199;
}

.login-form {
  float: left;
  position: absolute;
  border-radius: 10px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
